// component/ui/z-dropdown/z-dropdown.js
const path = '../z-dropdowns/z-dropdowns'
Component({
  relations: {
    [path]: {
      type: 'ancestor',
      linked: function (target) {},
      linkChanged: function (target) {},
      unlinked: function (target) {}
    }
  },

  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/,
  },

  /**
   * 组件的属性列表
   */
  properties: {
    value: {
      type: Object,
      value: {},
    },
    options: {
      type: Array,
      value: [],
    },
    title: {
      type: String,
      value: '',
    },
    name: {
      type: String,
      value: '',
    },
    disabled: {
      type: Boolean,
      value: false,
    },
    scroll: {
      type: Boolean,
      value: false,
    },
    isTop: {
      type: Boolean,
      value: false,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    isActive: false,
    current: '',
    treeDefaultOptions: {
      tier: 2,
      multiple: false,
      restrict: false,
      colors: ['#f0f0f0', '#f8f8f8', '#fff']
    },
    cascaderDefaultOptions: {
      defaultValue: [],
    }
  },

  /**
   * 组件的数据监听
   */
  observers: {
    options() {
      this.parent && this.parent.updateTabs()
    }
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    created() {
      Object.defineProperty(this, 'parent', {
        get: () => this.getRelationNodes(path)[0],
      });
    },
    attached: function () {},
    detached: function () {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    updateTitle(val) {
      this.setData({
        current: val || ''
      })
      this.parent && this.parent.updateTabs()
    },

    updateActive() {
      if (!this.parent) {
        return;
      }
      const {
        current,
      } = this.parent.data;
      const {
        children = []
      } = this.parent;
      const {
        name
      } = this.data;
      const index = children.indexOf(this);
      const currentName = String(name ? name : index);
      const isActive = current === currentName;
      this.setData({
        isActive
      });
    },

    onClose() {
      this.parent.toggle('')
    },

    onConfirm(e) {
      const {
        label,
      } = e.detail
      let arr = []
      Object.keys(label).forEach(item => {
        if (label[item]) {
          arr.push(label[item])
        }
      })
      this.updateTitle(arr.join(' '))
      this.triggerEvent('change', e.detail)
    },

    onClear() {
      this.setData({
        isActive: false,
        current: '',
      })
    },

  }
})